﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using LeadVinaglue.Models;
using LeadVinaglue.Models.ViewPages;
using LeadVinaglue.Repository;
using LeadVinaglue.Utility;

namespace LeadVinaglue.Controllers
{
    public class SignInController : BaseController
    {
        EFRoleProvider provider = new EFRoleProvider();
        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // GET: /Register/
        [DeviceFilterAttribute(Order = 1)]
        [CompressFilter(Order = 2)]
        public ActionResult Index()
        {
            RegisterManagementRepository repository = new RegisterManagementRepository();
            RegisterManagementModel model = new RegisterManagementModel();

            // Setup common
            SetupCommon(model);

            repository.GetModel(ref model, LeadConstant.REGISTER);
            ViewBag.ErrorMessage = "";

            return View(model);
        }

        [HttpPost]
        public ActionResult Index(FormCollection form, string returnUrl)
        {
            LogOnModel log = new LogOnModel();

            log.UserName = form["Email"].ToString();
            log.Password = EncryptionData.Encryption(form["Password"].ToString());
            log.RememberMe = (form["Remember"] != null && form["Remember"].ToString() == "on") ? true : false;

            UserRepository uRepository = new UserRepository();
            LeadVinaglue.User user = uRepository.GetSingle(log.UserName);


            if (MembershipService.ValidateUser(log.UserName, log.Password))
            {
                if (user.Active && user.IsLockedOut == false)
                {
                    // Update login counts
                    user.NumLogin = user.NumLogin == null ? 1 : user.NumLogin + 1;
                    uRepository.Save(user);

                    FormsService.SignIn(log.UserName, log.RememberMe);

                    // Get role to switch mode login
                    // Current: Login is default for client
                    EFRoleProvider provider = new EFRoleProvider();
                    string[] roles = provider.GetRolesForUser(log.UserName);
                    bool isAdmin = false;
                    bool isClient = false;

                    if (roles.Length > 0)
                    {
                        foreach (string role in roles)
                        {
                            if (role.ToUpper() == "SUPERADMINISTRATOR")
                            {
                                isAdmin = true;
                            }
                            else if (role.ToUpper() == "CLIENTADMIN")
                            {
                                isClient = true;
                            }
                        }

                        if (isAdmin)
                        {
                            if (Url.IsLocalUrl(returnUrl))
                            {
                                return Redirect(returnUrl);
                            }
                            else
                            {
                                return Redirect("/Management/Dashboard");
                            }
                        }
                        else if (isClient)
                        {
                            if (!string.IsNullOrEmpty(returnUrl))
                            {
                                return Redirect(returnUrl);
                            }
                            else
                            {
                                return Redirect("/MyAccount/Dashboard");
                            }
                        }
                    }
                }
                else
                {
                    ViewBag.ErrorMessage = "Tài khoản đang bị khóa, xin vui lòng liên hệ administrator để mở khóa.";
                }
            }
            else
            {
                ViewBag.ErrorMessage = "Tên đăng nhập hoặc mật khẩu cung cấp không chính xác.";
            }

            // If we got this far, something failed, redisplay form
            RegisterManagementRepository repository = new RegisterManagementRepository();
            RegisterManagementModel model = new RegisterManagementModel();

            // Setup common
            SetupCommon(model);

            repository.GetModel(ref model, LeadConstant.REGISTER);

            return View(model);
        }
    }
}
